<script setup lang="ts">
import { ref } from 'vue'
import {
  ElUpload,
  ElInput,
  ElProgress,
  ElMessage,
  ElButton,
  type UploadInstance,
  UploadProps
} from 'element-plus'
import { CloseBold } from '@element-plus/icons-vue'
import { Icon } from '@/components/Icon'
import { createImageViewer } from '@/components/ImageViewer'
import { uploadImg } from '@/api/utils/upload'
import { propTypes } from '@/utils/propTypes'

/**
 * 此组件为表单中上传单张图片时的需求封装
 * 默认开启进度条动画
 */
const props = defineProps({
  modelValue: propTypes.array.def(() => [])
})
const emit = defineEmits(['update:modelValue'])
const uploadFile = async (options) => {
  return await uploadImg(options.file)
}
const upload = ref<UploadInstance>()
const fileName = ref(props.modelValue)
// 上传成功时的参数拼接以及修改父组件绑定的value值
const onSuccess = (_response: IResponse) => {
  const url = `https://${_response.data.domain}/${_response.data.file_path}`
  emit('update:modelValue', [...props.modelValue, url])
  fileName.value = _response.data.file_name
}
const onError = (error) => {
  fileName.value = error
}
// 覆盖前一张图片的处理
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage({
    message: '图片不能超过6个！',
    type: 'warning'
  })
}

const openPreview = () => {
  if (!props.modelValue) return
  createImageViewer({
    urlList: props.modelValue
  })
}

// 删除图片方法
const deleteImage = (index) => {
  const updatedImages = [...props.modelValue]
  updatedImages.splice(index, 1)
  emit('update:modelValue', updatedImages)
}
// Progress
const showProgress = ref(false)
const progressStatus = ref<any>('')
const percentage = ref(0)
const onChange = (uploadFile) => {
  const percentageNum = {
    ready: 50,
    uploading: 80,
    success: 100,
    fail: 100
  }
  showProgress.value = uploadFile.status !== 'success'
  if (uploadFile.status === 'fail') progressStatus.value = 'exception'
  else progressStatus.value = 'success'
  percentage.value = percentageNum[uploadFile.status]
}
</script>
<template>
  <ElUpload
    ref="upload"
    :httpRequest="uploadFile"
    :onSuccess="onSuccess"
    :onError="onError"
    :onChange="onChange"
    :onExceed="handleExceed"
    :showFileList="false"
    :limit="6"
    class="w-full"
  >
    <ElInput v-model:modelValue="fileName" readonly :validate-event="false" style="width: 200px">
      <template #append>
        <Icon icon="ep:upload" :size="22" />
      </template>
    </ElInput>
    <ElProgress
      :percentage="percentage"
      v-show="showProgress"
      :status="progressStatus"
      :indeterminate="false"
      :show-text="false"
      class="mt-[10px] w-200px"
      @click.stop
    />
  </ElUpload>
  <!-- 添加图片展示部分 -->
  <div v-if="props.modelValue.length > 0" class="mt-[10px]">
    <div
      v-for="(image, index) in props.modelValue"
      :key="index"
      class="inline-block mr-[10px] position: relative"
    >
      <img
        :src="image"
        alt="Uploaded Image"
        style="width: 100px; height: 100px"
        @click="openPreview()"
      />
      <ElButton
        v-if="!image.uploading"
        :icon="CloseBold"
        size="small"
        circle
        @click="deleteImage(index)"
        class="delete-button"
      />
    </div>
  </div>
</template>
<style scoped>
.delete-button {
  position: absolute;
  top: -5px;
  right: -5px;
}
:deep(.el-upload) {
  display: block;
}
</style>
